package com.yanqu.road.server.manger;

import com.yanqu.road.logic.bussiness.servercenter.AppKeyBussiness;
import com.yanqu.road.entity.servercenter.AppKeyInfo;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.ConfigHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;

public class AppKeyMgr extends TempMgr {

	private static final Logger logger = LogManager.getLogger(AppKeyMgr.class.getName());

	private static Map<Long, AppKeyInfo> appKeyInfoMap;

	private static AppKeyInfo localAppKeyInfo;

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean init() throws Exception {
		return reload();
	}

	@Override
	public boolean reloadData() {
		appKeyInfoMap = AppKeyBussiness.getAppKeyInfoMap();
		if (appKeyInfoMap.size() <= 0) {
			logger.error("app key info is null，检查 t_s_app_key 是否存在配置");
			return false;
		}
		long serverId = Long.parseLong(ConfigHelper.getValue("serverId"));
		localAppKeyInfo = getAppKeyInfo(serverId);
		logger.info("key serverId : {}", serverId);
		return true;
	}

	@Override
	public boolean reloadConfig() throws Exception {
		return true;
	}

	public static AppKeyInfo getAppKeyInfo(long serverId){
		return appKeyInfoMap.get(serverId);
	}

	public static String getPlatformBaseUrl(){
		if(null != localAppKeyInfo){
			return localAppKeyInfo.getPlatformBaseUrl();
		}
		return "";
	}

	public static String getAndroidAppId(){
		if(null != localAppKeyInfo){
			return localAppKeyInfo.getAndroidAppId();
		}
		return "";
	}

	public static String getAndroidAppKey(){
		if(null != localAppKeyInfo){
			return localAppKeyInfo.getAndroidAppKey();
		}
		return "";
	}

	public static String getAndroidAppSecret(){
		if(null != localAppKeyInfo){
			return localAppKeyInfo.getAndroidAppSecret();
		}
		return "";
	}

	public static String getPlatformChannelId(){
		if(null != localAppKeyInfo){
			return localAppKeyInfo.getPlatformChannelId();
		}
		return "";
	}

	/**
	 * 找到一个对应的服务器Id
	 * @param appId
	 * @param channelId
	 * @return
	 */
	public static Long getServerIdByAppIDAndChanl(String appId, String channelId) {
		for (AppKeyInfo info : appKeyInfoMap.values()) {
			if (info.getAndroidAppId().equals(appId) && info.getPlatformChannelId().equals(channelId)) {
				return info.getServerId();
			}
		}
		return null;
	}
}
